package com.zzy.controller;



import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;


import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/*生产者同步发送消息*/
public class SendMsgTest {
    public final static String TOPIC_NAME = "my-replication-topic";

    public static String kafka_ip = "192.168.21.131:9092";


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //设置参数
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,  kafka_ip);

        //把发送的key从字符串序列化为字节数组
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //把发送消息value从字符串序列化为字节数组
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        //创建生产消息的客户端，传入参数
        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String,String>(properties);

        //创建消息
        //key：作用是决定往那个分区上发，value：具体要发送的消息内容
        ProducerRecord producerRecord = new ProducerRecord<>(TOPIC_NAME,"mykeyvalue","hellokafka111");

        //发送消息，得到消息发送的元数据并输出
        Future future = kafkaProducer.send(producerRecord);

        RecordMetadata recordMetadata = (RecordMetadata) future.get();

        System.out.println("同步发送消息结果："+"topic"+recordMetadata.topic()+"partition"+recordMetadata.partition()
                +"offset"+recordMetadata.offset());
    }

}
